package com.ch.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ch.web.ResponseDto.xyGz.XyGzFsCountResponse;
import com.ch.web.entity.user.XyGzEntity;
import com.ch.web.mapper.XyGzDao;
import com.ch.web.redis.UserMapCache;
import com.ch.web.requestDto.xyGzRequest.XyGzFsRequest;
import com.ch.web.service.XyGzService;
import com.ch.web.utils.PageUtils;
import com.ch.web.utils.Query;
import com.ch.web.utils.R;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


@Service("xyGzService")
public class XyGzServiceImpl extends ServiceImpl<XyGzDao, XyGzEntity> implements XyGzService {
    @Autowired
    UserMapCache userMapCache;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<XyGzEntity> page = this.page(
                new Query<XyGzEntity>().getPage(params),
                new QueryWrapper<XyGzEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public boolean getIsGzUser(Long currentUserId, Long userId) {
        QueryWrapper<XyGzEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("followers_id", currentUserId).eq("followers_gz_id", userId);
        XyGzEntity one = this.getOne(wrapper);
        return !ObjectUtils.isEmpty(one);
    }

    @Override
    public boolean save(XyGzEntity xyGz, HttpServletRequest request) {
        //当前用户id
        Long userId = userMapCache.getUserIdByToken(request);
        xyGz.setFollowersId(userId);
        return this.save(xyGz);
    }

    @Override
    public R cancelGz(XyGzEntity xyGzEntity, HttpServletRequest request) {
        //当前用户id
        Long userId = userMapCache.getUserIdByToken(request);
        xyGzEntity.setFollowersId(userId);
        return R.okOrError(this.getBaseMapper().deleteEntity(xyGzEntity));
    }

    @Override
    public R getUserGzCount(XyGzEntity xyGzEntity) {
        //构造一个装饰器
        QueryWrapper<XyGzEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("followers_id", xyGzEntity.getFollowersId());
        int size = this.list(wrapper).size();
        return R.ok().put("gzCount", size);
    }

    @Override
    public XyGzFsCountResponse getUserFsCount(XyGzFsRequest xyGzFsRequest) {
        QueryWrapper<XyGzEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("followers_gz_id", xyGzFsRequest.getFollowersGzId());
        int size = this.list(wrapper).size();
        XyGzFsCountResponse gzFsCountResponse = new XyGzFsCountResponse();
        gzFsCountResponse.setFsCount(size);
        return gzFsCountResponse;
    }
}